package com.ollobot.authorization.service;

import com.ollobot.authorization.entity.User;
import com.ollobot.authorization.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UserService implements UserDetailsService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return userRepository.findByUsername(username)
                .or(() -> userRepository.findByEmail(username))
                .orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
    }

    @Transactional
    public User createUser(String email, String firstName, String lastName) {
        if (userRepository.existsByEmail(email)) {
            throw new RuntimeException("Email already exists: " + email);
        }

        User user = new User();
        user.setEmail(email);
        user.setUsername(email); // 使用邮箱作为用户名
        user.setFirstName(firstName);
        user.setLastName(lastName);
        user.setProvider(User.AuthProvider.LOCAL);
        user.setEmailVerified(true); // 通过邮箱验证码登录，认为邮箱已验证
        user.setEnabled(true);

        userRepository.insert(user);
        return user;
    }

    @Transactional
    public User createOrUpdateOAuthUser(String email, String firstName, String lastName, 
                                       String avatarUrl, User.AuthProvider provider, String providerId) {
        Optional<User> existingUser = userRepository.findByProviderAndProviderId(provider, providerId);
        
        if (existingUser.isPresent()) {
            // 更新现有用户信息
            User user = existingUser.get();
            user.setFirstName(firstName);
            user.setLastName(lastName);
            user.setAvatarUrl(avatarUrl);
            user.setEmailVerified(true);
            userRepository.updateById(user);
            return user;
        }

        // 检查是否已存在相同邮箱的用户
        Optional<User> userByEmail = userRepository.findByEmail(email);
        if (userByEmail.isPresent()) {
            // 如果存在相同邮箱的用户，更新其OAuth信息
            User user = userByEmail.get();
            user.setProvider(provider);
            user.setProviderId(providerId);
            user.setFirstName(firstName);
            user.setLastName(lastName);
            user.setAvatarUrl(avatarUrl);
            user.setEmailVerified(true);
            userRepository.updateById(user);
            return user;
        }

        // 创建新用户
        User newUser = new User();
        newUser.setEmail(email);
        newUser.setUsername(email);
        newUser.setFirstName(firstName);
        newUser.setLastName(lastName);
        newUser.setAvatarUrl(avatarUrl);
        newUser.setProvider(provider);
        newUser.setProviderId(providerId);
        newUser.setEmailVerified(true);
        newUser.setEnabled(true);

        userRepository.insert(newUser);
        return newUser;
    }

    public Optional<User> findByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public boolean existsByEmail(String email) {
        return userRepository.existsByEmail(email);
    }

    @Transactional
    public User registerUser(String username, String email, String password, String firstName, String lastName) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(username)) {
            throw new RuntimeException("Username already exists: " + username);
        }
        
        // 检查邮箱是否已存在
        if (userRepository.existsByEmail(email)) {
            throw new RuntimeException("Email already exists: " + email);
        }

        // 创建新用户
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setEmail(email);
        newUser.setPassword(passwordEncoder.encode(password)); // 加密密码
        newUser.setFirstName(firstName);
        newUser.setLastName(lastName);
        newUser.setProvider(User.AuthProvider.LOCAL);
        newUser.setEmailVerified(false); // 注册时邮箱未验证
        newUser.setEnabled(true);

        userRepository.insert(newUser);
        return newUser;
    }

    public Optional<User> findById(Long id) {
        return Optional.ofNullable(userRepository.selectById(id));
    }

    @Transactional
    public void deleteUser(Long userId) {
        User user = userRepository.selectById(userId);
        if (user == null) {
            throw new RuntimeException("User not found: " + userId);
        }
        
        // 软删除用户（设置为禁用状态）
        user.setEnabled(false);
        userRepository.updateById(user);
        
        // 或者硬删除用户（完全删除记录）
        // userRepository.deleteById(userId);
    }

    @Transactional
    public void permanentDeleteUser(Long userId) {
        User user = userRepository.selectById(userId);
        if (user == null) {
            throw new RuntimeException("User not found: " + userId);
        }
        
        // 硬删除用户
        userRepository.deleteById(userId);
    }
}
